<!-- 图片帧动画组件 -->
<template>
	<div class="ma-frame-canvas" @touchmove.stop>
		<!-- <canvas @touchstart="onStart" @touchmove="onMove" @touchend="onEnd" class="frame-canvas" canvas-id="frame-canvas"></canvas> -->
		<canvas 
		type="2d" 
		id="canvas" 
		class="frame-canvas"
		@touchstart="onStart"
		@touchmove="onMove"
		@touchend="onEnd"
		style="background-color: skyblue;"
		>
		</canvas>
		<!-- <video 
		src="https://img.xiangxiangad.com/frame/video.mp4" 
		:controls="false"
		:show-center-play-btn="false"
		id="video"
		@touchstart="onVideoStart"
		@touchmove="onVideoMove"
		@touchend="onVideoEnd"
		>
		</video> -->
	</div>
</template>

<script>
	export default {
		data(){
			return {
				imgList: [],
				startY: 0,
				imgIndex: 0,
				window: {
					height: 0,
					width: 0
				},
				ctx: null,
				promiseList: [],
				intervalTime: 30,
				canvas: null
			}
		},
		methods: {
			init(res){
				console.log(res)
				const { width,height } = res[0];
				this.window = { width,height };
				const canvas = res[0].node
				canvas.height = height;
				canvas.width = width;
				const ctx = canvas.getContext('2d')
				this.ctx = ctx;
				this.canvas = canvas;
				let i = 0
				let frame;
				uni.showLoading({mask: true})
				const renderLoop = () => {
					// canvas.width = width;
					// canvas.height = height;
					let src = this.getSrc(i);
					let index = i;
					let img = canvas.createImage();
					img.onload = () => {
						this.imgList[index] = img
						if(index == 0) {
							console.log('画第一张')
							ctx.drawImage(img,0,0,width,height);
						}else if(index == 20){
							uni.hideLoading()
						}
					}
					img.src = src
					if(i == 388) return;
					i++;
					// if(this._img){
					// 	ctx.drawImage(this._img,0,0,width,height)
					// 	// ctx.draw();
					// 	return;
					// }
					// this._render(canvas,ctx);
					canvas.requestAnimationFrame(renderLoop);
				}
				canvas.requestAnimationFrame(renderLoop)
				// console.log(canvas.requestAnimationFrame(renderLoop))
				
				// const img = canvas.createImage()
				
				// img.onload = () => {
				// 	this._img = img
				// 	console.log(img)
				// }
				
				// img.src = 'https://img.xiangxiangad.com/frame/202203052213_00000.jpg'
				// ctx.drawImage()
			},
			loop(canvas,ctx){
				
			},
			getDom(className){
				return new Promise((resolve,reject) => {
					var query = uni.createSelectorQuery().in(this);
					query.select(className).boundingClientRect(rect => {
						// console.log(rect);
						resolve(rect)
					}).exec();
				})
			},
			onStart(e){
				const { y } = e.changedTouches[0];
				this.startY = y;
			},
			//判断一个imgIndex是否在区间里
			isBetween(interval = [10,80]){
				const [min,max] = interval;
				if(this.imgIndex >= min && this.imgIndex <= max) return true;
				else return false;
			},
			onMove(e){
				// console.log(e)
				const { y } = e.changedTouches[0];
				if(y - this.startY < 0) {
					this.startY = y;
					if(this.isBetween([5,80])){
						this.onInterval({
							interval: [5,80],
							key: 'timer1'
						})
					}else if(this.isBetween([81,175])){
						this.onInterval({
							interval: [81,175],
							key: 'timer2'
						})
					}else if(this.isBetween([176,266])){
						this.onInterval({
							interval: [176,266],
							key: 'timer3'
						})
					}else if(this.isBetween([267,351])){
						this.onInterval({
							interval: [267,351],
							key: 'timer4'
						})
					}else if(this.isBetween([352,387])){
						this.onInterval({
							interval: [352,387],
							key: 'timer5'
						})
					}else if(this.imgIndex < 388){
						this.imgIndex++;
						this.onDraw();
					}
					// if(this.imgIndex < 388){
					// 	this.imgIndex++;
					// 	this.onDraw();
					// }
				}else if(y - this.startY > 0) {
					this.startY = y;
					if(this.isBetween([5,80])){
						this.onInterval({
							interval: [5,80],
							key: 'timer1',
							reverse: true
						})
					}else if(this.isBetween([81,175])){
						this.onInterval({
							interval: [81,175],
							key: 'timer2',
							reverse: true
						})
					}else if(this.isBetween([176,266])){
						this.onInterval({
							interval: [176,266],
							key: 'timer3',
							reverse: true
						})
					}else if(this.isBetween([267,351])){
						this.onInterval({
							interval: [267,351],
							key: 'timer4',
							reverse: true
						})
					}else if(this.isBetween([352,387])){
						this.onInterval({
							interval: [352,387],
							key: 'timer5',
							reverse: true
						})
					}else if(this.imgIndex > 0){
						this.imgIndex--;
						this.onDraw();
					}
					
					// if(this.imgIndex > 0){
					// 	this.imgIndex--;
					// 	this.onDraw();
					// }
				}
			},
			onEnd(){
				// console.log(this.imgIndex)
			},
			//执行动画的定时器
			onInterval({ interval = [10,80],timer = 'timer1',reverse = false } = {}){
				let [minVal,maxVal] = interval;
				let timerName = reverse ? `${timer}_reverse` : timer;
				if(this[timer] || this[`${timer}_reverse`]) return;
				this[timerName] = setInterval(() => {
					let conditions = reverse ? (this.imgIndex < minVal) : (this.imgIndex > maxVal);
					//超出范围就销毁定时器
					if(conditions){
						clearInterval(this[timerName]);
						this[timerName] = null;
						return;
					}
					if(reverse) this.imgIndex--;
					else this.imgIndex++;
					this.onDraw();
				},this.intervalTime)
			},
			onDraw(){
				return new Promise((resolve,reject) => {
					let { ctx,imgIndex,imgList } = this;
					let { width,height } = this.window;
					ctx.clearRect(0,0,width,height)
					ctx.drawImage(imgList[imgIndex],0,0,width,height)
					// ctx.draw();
				})
			},
			getImageInfo(src){
				return new Promise((resolve,reject) => {
					uni.getImageInfo({
						src,
						success: res => {
							// console.log(res)
							resolve(res.path)
						},
						fail: err => {
							console.log(err)
						}
					})
				})
			},
			getSrc(i){
				let imgEnd = ''
				if(i < 10) imgEnd = `0000${i}`;
				else if(i >= 10 && i < 100) imgEnd = `000${i}`;
				else imgEnd = `00${i}`;
				return `https://img.xiangxiangad.com/frame/202203052213_${imgEnd}.jpg`;
			},
			async render(isShowLoading = true){
				if(isShowLoading){
					uni.showLoading({
						mask:true
					})
				}
				for(let i = 0;i <= 388;i++){
					this.imgIndex = i;
					this.onDraw();
				}
				this.imgIndex = 0;
				this.onDraw();
				uni.hideLoading()
			},
			onVideoStart(e){
				if(!this.video) this.video = uni.createVideoContext('video',this);
				if(!this.videoSeekTime) this.videoSeekTime = 0;
				const { pageY } = e.changedTouches[0];
				this.videoStartY = pageY;
			},
			onVideoMove(e){
				// console.log(e)
				const { pageY } = e.changedTouches[0];
				if(this.videoStartY < pageY){
					this.videoSeekTime++;
					this.video.seek(this.videoSeektime);
				}
			},
			onVideoEnd(e){
				
			}
		},
		mounted(){
			uni.createSelectorQuery()
			.in(this)
			.select('#canvas')
			.fields({
				node: true,
				size: true
			}).exec(this.init.bind(this))
			
			return;
			this.ctx = uni.createCanvasContext('frame-canvas',this)
			this.getDom('.frame-canvas').then(async res => {
				// console.log(res)
				if(!res) return;
				let { width,height } = res;
				this.window = { width,height };
				let _imgList = uni.getStorageSync('imgList');
				if(!_imgList){
					console.log('没缓存,先下载图片')
					uni.showLoading({
						mask: true
					})
					for(let i = 0;i <= 388;i++){
						let src = this.getSrc(i);
						this.promiseList.push(this.getImageInfo(src));
					}
					Promise.all(this.promiseList).then(imgList => {
						// console.log(imgList)
						this.imgList = imgList;
						uni.setStorageSync('imgList',imgList);
						console.log('图片下载ok')
						this.render(false);
					})
				}else {
					console.log('有缓存')
					this.imgList = _imgList;
					this.render();
				}
			})
		}
	}
</script>

<style lang="scss">
	.ma-frame-canvas{
		position: relative;
		height: 100%;
		width: 100%;
		.frame-canvas {
			width: 100%;
			height: 100%;
			position: fixed;
			bottom: 0;
			z-index: 9999;
		}
		video{
			position: fixed;
			height: 100%;
			width: 100%;
			background-color: blue;
			z-index: 9999999999;
		}
	}
</style>
